package splug.cjk;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

import splug.cjk.packet.BBSCarPoolPacket;
import splug.cjk.packet.FriendPacket;

public class PersonInfoRead extends Thread {

	private InputStream is;
	private OutputStream os;
	private ArrayList<String> info = new ArrayList<String>();

	public PersonInfoRead(InputStream is, OutputStream os) {
		super();
		this.is = is;
		this.os = os;
	}


	@Override
	public void run() {
		super.run();
		try {
			//요청 하는 사람의 ID를 받아온다
			ObjectInputStream input = new ObjectInputStream(is);
			FriendPacket packet = (FriendPacket) input.readObject();
			String id = packet.getId();

			Class.forName("com.mysql.jdbc.Driver");
			Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/carpool?useUnicode=true&characterEncoding=euckr","root","apmsetup");
			Statement stmt = conn.createStatement();

			//해당하는 회원이 있는지 검사한다
			String query1 = "select id, name, car, phone, mail from member;";

			ResultSet rs = stmt.executeQuery(query1);

			boolean isFound = false;

			while(rs.next()){
				String str = rs.getString("id");
				if(str.equals(id)){
					isFound = true;
					//해당하는 회원을 찾았다는 신호를 먼저 보내주고
					os.write('1');
					os.flush();

					//그다음에 회원의 정보를 넘겨준다
					info.add(str);
					info.add(rs.getString("name"));
					info.add(rs.getString("car"));
					info.add(rs.getString("phone"));
					info.add(rs.getString("mail"));
				}

			}

			if(isFound){
				//해당 유저가 몇번이나 신고를 당했는지 세어본다
				String query = "select count(you) from report where you = '"
					+ id + "'";
				rs = stmt.executeQuery(query);
				int count = 0;
				while(rs.next()){
					count = rs.getInt(1);
				}

				info.add(Integer.toString(count));

				ObjectOutputStream output = new ObjectOutputStream(os);
				packet = new FriendPacket(info, null, null);
				output.writeObject(packet);
			}

			else{
				//해당하는 회원이 없으면 '0'번 응답을 보내준다
				os.write('0');
				os.flush();
			}

		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
